<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\RoleRequest;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    public function index(){

        $roles = Role::withCount('permissions')->orderByDesc('id')->paginate(request('page_size', 10));

        return view('backend.role.index',compact('roles'));
    }

    public function create(){

        return view('backend.role.create');
    }

    public function store(
        RoleRequest $request,
        Role $role
    ){
        $role->fill($request->filldata())->save();
        flash('角色添加成功', 'success');

        return back();
    }

    public function edit($id)
    {
        $role = Role::findOrFail($id);

        return view('backend.role.edit', compact('role'));
    }

    public function update(RoleRequest $request, $id)
    {
        $role = Role::findOrFail($id);
        $role->fill($request->filldata())->save();
        flash('角色编辑成功', 'success');

        return back();
    }

    public function destroy($id)
    {
        $role = Role::findOrFail($id);
        //TODO::判断该角色下是否还有管理人员
//        if ($role->administrators()->exists()) {
//            flash('该角色下还存在管理员，请先删除相应的管理员');
//        } else {
            $role->delete();
            flash('删除成功', 'success');
        //}

        return back();
    }


    public function showSelectPermissionPage($id)
    {
        //app()['cache']->forget('spatie.permission.cache');
        $role = Role::findOrFail($id);

        $permissions = Permission::where('guard_name',$role->guard_name)->get();

        return view('backend.role.select_permission', compact('permissions', 'role'));
    }

    public function handlePermissionSave(Request $request, $id)
    {
        $role = Role::findOrFail($id);
        $role->givePermissionTo($request->input('permission_names', []));
        flash('授权成功', 'success');

        return back();
    }
}
